//
//  WXApiRequestHandler.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/4.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

struct WXPayResult: HandyJSON {
    var timestamp: UInt32 = 0
    var package: String = ""
    var appid: String = ""
    var sign: String = ""
    var partnerid: String = ""
    var prepayid: String = ""
    var noncestr: String = ""
    
    // MARK: - 后台自定义字段
    var getType: Int = 0
    var ownAmount: String = ""
}

class WXApiRequestHandler: NSObject {
    /// 微信支付前统一下单
    class func wxPaySubmitOrder(orderId: String,
                                orderAmount: String,
                                receiveId: String = "",
                                orderType: OrderType,
                                receiveType: PrescriptionOrderReceiveType = .express,
                                success: @escaping (_ model: WXPayResult) -> Void,
                                failure: @escaping (_ errorMsg: String?, String?) -> Void) {
        let paras: [String: Any]
        switch orderType {
        case .advisory, .cloud:
            paras = [
                "orderId": orderId,
                "orderAmount": orderAmount
            ]
        case .prescription:
            if receiveType == .express {
                paras = [
                    "orderId": orderId,
                    "orderAmount": orderAmount,
                    "receiveId": receiveId,
                ]
            } else {
                paras = [
                    "orderId": orderId,
                    "orderAmount": orderAmount,
                    "getType": receiveType.rawValue
                ]
            }
        case .nurse:
            paras = [
                "orderId": orderId,
                "orderAmount": orderAmount,
            ]
        }
        var target = ApiManager.wxPaySubmitOrder(paras: paras)
        switch orderType {
        case .advisory,.cloud,.prescription:
            target = ApiManager.wxPaySubmitOrder(paras: paras)
        case .nurse:
            target = ApiManager.wxPayNurseSubmitOrder(paras: paras)
        }
        
        HttpTool.shared.request(target: target, success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description, json["code"].description)
            case .success:
                if let model = JSONDeserializer<WXPayResult>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍后重试", nil)
                }
            }
        }) { errorMsg in
            failure(errorMsg, nil)
        }
    }
    
    /// 调用后台获取相应参数并生成预订单
    static func generateWXPayOrder(model: WXPayResult) {
        let request = PayReq()
        request.partnerId = model.partnerid
        request.prepayId = model.prepayid
        request.package = "Sign=WXPay"
        request.nonceStr = model.noncestr
        request.timeStamp = model.timestamp
        request.sign = model.sign
        let _ = WXApi.send(request)
    }
    
    /// 生成签名
    static private func generateSignForWXPay(paras: [String: Any]) -> String {
        var _paramters = [String: Any]()
        
        for (key, value) in paras {
            if let str = value as? String, str == "" {
                continue
            }
            
            _paramters[key] = value
        }
        
        let sortedKeys = _paramters.keys.sorted()
        var temp = sortedKeys.map({ "\($0)=\(_paramters[$0]!)" }).joined(separator: "&")
        temp += "&key=64255ed288e44b7298f49a1239103d15"
        
        return temp.md5.uppercased()
    }
}
